/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.database.dao;

import org.codeminer.database.DatabaseConnection;
import org.codeminer.database.DatabaseException;
import org.codeminer.parts.database.sql.From;
import org.codeminer.parts.database.sql.SQL;
import org.codeminer.parts.library.Album;
import org.codeminer.parts.library.Artist;
import org.codeminer.parts.library.Song;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public final class SongDAO extends DAO {
    
    private SongDAO() {
    }
    
    public static long store(Song song, DatabaseConnection connection) throws DatabaseException {
        connection.accuireWriteLock();
        try {
            updateAndGetNextId(connection, song);
            String insertStatement = SQL.insertInto("Songs").
                    values().
                    value(song.getOid()).
                    value(song.getTitle()).
                    value(song.getTrackNumber()).
                    value(song.getFile().getAbsolutePath()).
                    value(song.getDuration()).toSQL();
            
            executeInsert(connection, insertStatement);
            return song.getOid();
        } finally {
            connection.releaseWriteLock();
        }
    }
    
    public static List<Song> get(Song searchCriteria, DatabaseConnection connection) throws DatabaseException {
        ResultSet resultSet = null;
        connection.accuireReadLock();
        try {
            String query = null;
            From select = SQL.select().from("Songs");
            if (searchCriteria == null) {
                query = select.toSQL();
            } else if (searchCriteria.getOid() != -1) { //search by oid
                query = select.where("Song_Id").is(searchCriteria.getOid()).toSQL();
            } else if (searchCriteria.getTitle() != null) { //search by title
                query = select.where("Title").is(searchCriteria.getTitle()).toSQL();
            } else if (searchCriteria.getFile() != null) { //search by file
                query = select.where("Filepath").is(searchCriteria.getFile().getAbsolutePath()).toSQL();
            } else {
                throw new IllegalArgumentException("unhandled search criteria");
            }
            resultSet = connection.createStatement().executeQuery(query);
            List<Song> result = new LinkedList<>();
            while (resultSet.next()) {
                long oid = resultSet.getLong("Song_Id");
                String title = resultSet.getString("Title");
                int trackNumber = resultSet.getInt("Song_Number");
                File file = new File(resultSet.getString("Filepath"));
                double duration = resultSet.getDouble("Duration");
                final Song song = new Song(title, trackNumber, duration, file);
                song.setOid(oid);
                result.add(song);
            }
            return result;
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        } finally {
            connection.releaseReadLock();
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException ignored) {

                }
            }
        }
    }
    
    public static List<Song> getSongsForAlbum(Album album, DatabaseConnection connection) throws DatabaseException {
        connection.accuireReadLock();
        try {
            if (album.getOid() == -1) {
                throw new IllegalArgumentException("Album should already be persisted");
            }
            
            String query = SQL.select("Song_Id").from("SONGS_FOR_ALBUM").where("Album_Id").is(album.getOid()).toSQL();
            List<Long> songIds = queryIds(query, "Song_Id", connection);
            
            List<Song> result = new LinkedList<>();
            for (Long songId : songIds) {
                result.addAll(get(Song.byOId(songId), connection));
            }
            return result;
        } finally {
            connection.releaseReadLock();
        }
    }
    
    public static List<Song> getSongsForArtist(Artist artist, DatabaseConnection connection) throws DatabaseException {
        connection.accuireReadLock();
        try {
            if (artist.getOid() == -1) {
                throw new IllegalArgumentException("Artist should already be persisted");
            }
            
            String query = SQL.select("Song_Id").from("ARTIST_FOR_SONGS").where("Artist_Id").is(artist.getOid()).toSQL();
            List<Long> songIds = queryIds(query, "Song_Id", connection);
            
            List<Song> result = new LinkedList<>();
            for (Long songId : songIds) {
                result.addAll(get(Song.byOId(songId), connection));
            }
            return result;
        } finally {
            connection.releaseReadLock();
        }
    }
    
    public static void addArtistToSong(Song song, Artist artist, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiables(artist, song);
        
        List<Song> songsForArtist = getSongsForArtist(artist, connection);
        if (songsForArtist.contains(song)) {
            return;
        }
        
        String insert = SQL.insertInto("ARTIST_FOR_SONGS").values().value(song.getOid()).value(artist.getOid()).toSQL();
        connection.accuireWriteLock();
        try {
            executeInsert(connection, insert);
        } finally {
            connection.releaseWriteLock();
        }
    }
    
    public static List<Artist> getArtistsForSong(Song song, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(song);
        connection.accuireReadLock();
        try {
            
            String query = SQL.select("Artist_Id").from("ARTIST_FOR_SONGS").where("Song_Id").is(song.getOid()).toSQL();
            List<Long> songIds = queryIds(query, "Artist_Id", connection);
            
            List<Artist> result = new LinkedList<>();
            for (Long artistId : songIds) {
                result.add(ArtistDAO.get(Artist.getOIdCriteria(artistId), connection));
            }
            return result;
        } finally {
            connection.releaseReadLock();
        }
    }
    
    public static boolean delete(Song song, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(song);
        
        connection.accuireWriteLock();
        try {
            String deleteStatement = SQL.delete().from("Songs").where("Song_Id").is(song.getOid()).toSQL();
            return executeUpdate(connection, deleteStatement);
        } finally {
            connection.releaseWriteLock();
        }
    }
    
    public static boolean update(Song song, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(song);
        
        connection.accuireWriteLock();
        try {
            String query = SQL.update("Songs").
                    set("Title", song.getTitle()).
                    set("Song_Number", song.getTrackNumber()).
                    set("Filepath", song.getFile().getAbsolutePath()).
                    set("Duration", song.getDuration()).
                    where("Song_Id").is(song.getOid()).toSQL();
            return executeUpdate(connection, query);
        } finally {
            connection.releaseWriteLock();
        }
    }
}
